const axios = require('axios');
const md5 = require('md5');
const { nowDate, uuid } = require('../utils/tools');

class XunhuPayService {
  constructor(config) {
    this.appId = config.appId;
    this.appSecret = config.appSecret;
    this.notifyUrl = config.notifyUrl;
    this.returnUrl = config.returnUrl;
    this.apiUrl = 'https://api.xunhupay.com/payment/do.html';
  }

  /**
   * 生成签名哈希
   * @param {Object} params - 请求参数
   * @returns {string} - 签名哈希
   */
  getHash(params) {
    const sortedParams = Object.keys(params)
      .filter(key => params[key] && key !== 'hash') // 过滤掉空值和hash本身
      .sort()
      .map(key => `${key}=${params[key]}`)
      .join('&');
    const stringSignTemp = sortedParams + this.appSecret;
    return md5(stringSignTemp);
  }

  /**
   * 验证支付通知签名
   * @param {Object} notifyData - 通知数据
   * @returns {boolean} - 验证结果
   */
  verifyNotify(notifyData) {
    const receivedHash = notifyData.hash;
    return receivedHash === this.getHash(notifyData);
  }

  /**
   * 创建微信支付
   * @param {Object} options - 支付选项
   * @returns {Promise} - 支付结果
   */
  async createWxPay(options) {
    return this.createPayment(options, 'wxpay');
  }

  /**
   * 创建支付宝支付
   * @param {Object} options - 支付选项
   * @returns {Promise} - 支付结果
   */
  async createAliPay(options) {
    return this.createPayment(options, 'alipay');
  }

  /**
   * 创建支付
   * @param {Object} options - 支付选项
   * @param {string} channel - 支付渠道 (wxpay/alipay)
   * @returns {Promise} - 支付结果
   */
  async createPayment(options, channel) {
    const params = {
      version: '1.1',
      appid: this.appId,
      trade_order_id: options.orderId,
      total_fee: options.amount,
      title: options.title,
      description: options.description || '',
      time: nowDate(),
      notify_url: this.notifyUrl,
      return_url: this.returnUrl,
      nonce_str: uuid(),
      channel: channel,
    };

    // 移动端支付配置
    if (options.isMobile) {
      params.type = 'WAP';
      params.wap_url = 'https://www.xunhupay.com';
      params.wap_name = 'XunhuPay';
    }

    // 生成签名
    const hash = this.getHash(params);

    try {
      // 发送请求
      const response = await axios.post(this.apiUrl, 
        { ...params, hash }, 
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          }
        }
      );

      if (response.data && response.data.status === 'ok') {
        return {
          success: true,
          paymentId: response.data.trade_no,
          qrCodeUrl: response.data.url_qrcode,
          payUrl: response.data.url,
          data: response.data
        };
      } else {
        throw new Error(response.data.error || '创建支付订单失败');
      }
    } catch (error) {
      console.error('虎皮椒支付请求失败:', error);
      throw error;
    }
  }

  /**
   * 查询订单状态
   * @param {string} orderId - 订单ID
   * @returns {Promise} - 查询结果
   */
  async queryOrderStatus(orderId) {
    const params = {
      version: '1.1',
      appid: this.appId,
      trade_order_id: orderId,
      time: nowDate(),
      nonce_str: uuid(),
    };

    // 生成签名
    const hash = this.getHash(params);

    try {
      const response = await axios.post(
        'https://api.xunhupay.com/payment/query.html',
        { ...params, hash },
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          }
        }
      );
      return response.data;
    } catch (error) {
      console.error('查询订单状态失败:', error);
      throw error;
    }
  }
}

module.exports = XunhuPayService;